package com.googlecode.afdbaccess.web.common.interceptors;

import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

import org.apache.log4j.Logger;

import com.googlecode.afdbaccess.config.injectconfig.RequestTransaction;

public class RollbackAtExceptionInterceptor {
    private final static Logger log = Logger.getLogger(RollbackAtExceptionInterceptor.class);

    @Inject
    private RequestTransaction t;

    @AroundInvoke 
    public Object rollbackAtException(InvocationContext ctx) throws Exception {
        Object returnObject;
        boolean completed = false;

        try {
            returnObject = ctx.proceed();
            completed = true;
        } finally {
            if(!completed) {
                log.info("Rolling back transaction since method didn't complete properly. Exception will be handled below.");
                t.rollback();
            }
        }
        return returnObject;
    }

}